<script setup>
import { ref, watch } from "vue";
import router from "@/router";
import { Search as SearchOutlined } from "@element-plus/icons-vue";
import { Edit, Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  selectTaskManagerList,
  selectClassList,
  BytwoIdGetTaskManagerList,
  updateTaskList,
} from "@/api/common/work/SelectWorkList.js";
import * as XLSX from 'xlsx';

const taskList = ref([]);

const classId = ref();

const BytwoIdGetTaskList = async () => {
  if (classId.value != 0) {
    let result = await BytwoIdGetTaskManagerList(classId.value);
    taskList.value = result.data;
    for (let i = 0; i < taskList.value.length; i++) {
      if (taskList.value[i].score == null) {
        taskList.value[i].s = "未评分";
      } else {
        taskList.value[i].s = taskList.value[i].score;
      }

      if (taskList.value[i].approvalStatus == 0) {
        taskList.value[i].a = "已批复";
        taskList.value[i].p = "修改批复";
      } else {
        taskList.value[i].a = "未批复";
        taskList.value[i].p = "批复";
      }
    }
  } else {
    taskManagerList()
  }
}
const taskManagerList = async () => {
  let res = await selectTaskManagerList();
  taskList.value = res.data;
  for (let i = 0; i < taskList.value.length; i++) {
    if (taskList.value[i].score == null) {
      taskList.value[i].s = "未评分";
    } else {
      taskList.value[i].s = taskList.value[i].score;
    }

    if (taskList.value[i].approvalStatus == 0) {
      taskList.value[i].a = "已批复";
      taskList.value[i].p = "批复作业";
    } else {
      taskList.value[i].a = "未批复";
      taskList.value[i].p = "批复";
    }
  }
};
taskManagerList();
const a = ref([]);
const s = ref([]);
const p = ref([]);
const classList = ref([]);
const getClassList = async () => {
  let res = await selectClassList();
  classList.value = res.data;
};
getClassList();

const filteredOptions2 = ref([]);

const filteredOptions1 = ref([]);

const updateSecondDropdown1 = () => {
  filteredOptions2.value = options1.filter(
    (option) => option.value !== selected1.value
  );
};

const updateSecondDropdown2 = () => {
  filteredOptions1.value = options2.filter(
    (option1) => option1.value !== selected3.value
  );
};

const drawer = ref(false);

const pf = (row) => {
};
const updataList = ref({
  id: "",
  score: "",
  comment: "",
});
// 校验函数  
function validateInputs(score, comment) {
  const errors = [];

  if (!score || isNaN(parseFloat(score)) || !isFinite(score)) {
    errors.push('分数必须是一个有效的数字');
  }

  if (comment && comment.trim().length === 0) {
    errors.push('评论不能为空（如果填写了的话）');
  }

  // 可以添加更多校验规则  

  return errors;
}

const updateworklist = async () => {
  const errors = validateInputs(workList.value.score, workList.value.comment);

  if (errors.length > 0) {
    // 如果有错误，则显示错误信息  
    ElMessage.error(errors.join('<br/>'));
    return; // 停止执行后续代码  
  }

  // 如果没有错误，则继续更新数据  
  updataList.value.score = workList.value.score;
  updataList.value.comment = workList.value.comment;
  let res = await updateTaskList(updataList.value); // 假设updateTaskList是一个已定义的异步函数  

  if (res.success || res.code === 200 || res.status === 'success') { // 根据实际返回值的结构来调整  
    ElMessage.success("修改成功");
    drawer.value = false;
    taskManagerList(); // 假设taskManagerList是一个用于刷新列表的函数  
  } else {
    ElMessage.error("修改失败: " + res.message || "未知错误");
  }
  // 设置延时，比如2秒后刷新页面  
  setTimeout(() => {
    window.location.reload(true);
  }, 500); // 2000毫秒后执行  
};
const workList = ref({
  nickName: "",
  taskName: "",
  taskTxt: "",
  submitTime: "",
  submitCount: "",
  attachmentUrl: "",
  imageUrl: "",
  taskInfo: "",
  score: "",
  comment: "",
  attachmentRealUrl: ''
});
const srcList = ref([])
const workpfList = (row) => {
  //console.log(row)
  updataList.value.id = row.id;
  workList.value.nickName = row.nickName;
  workList.value.taskName = row.taskName;
  workList.value.taskTxt = row.taskTxt;
  workList.value.submitTime = row.submitTime;
  workList.value.submitCount = row.submitCount;
  workList.value.attachmentUrl = row.attachmentUrl;
  workList.value.imageUrl = row.imageUrl;
  workList.value.taskInfo = row.taskInfo;
  workList.value.score = row.score;
  workList.value.comment = row.comment;
  workList.value.imageUrl = row.imageUrl;
  workList.value.attachmentUrl = row.attachmentUrl;
  //console.log(row.attachmentUrl.indexOf("%"))
  let percentIndex = row.attachmentUrl.indexOf("%")
  let result = percentIndex !== -1 ? row.attachmentUrl.substring(percentIndex + 1) : row.attachmentUrl;

  workList.value.attachmentRealUrl = decodeURIComponent(decodeURIComponent(result))

  srcList.value = row.taskImgUrl
};

const fontSize = ref(0)
const addSize = () => {
  if (workList.value.comment) {
    fontSize.value = workList.value.comment.length
  }
}


watch(() => {
  addSize()
})

const downloadFile = (url) => {
  const link = document.createElement("a");
  link.href = url; // 假设 `path` 是文件的 URL
  link.download = ""; // 可以设置下载文件的名字
  link.click();
};



const exportToExcel = () => {
  const columns = ["姓名", "提交时间", "提交次数", "批复状态", "评分", "管理"];

  // 初始化dataArray为包含列名的二维数组  
  const dataArray = [columns];
  // 假设taskList是已经定义好的包含多个对象的数组  
  taskList.value.forEach(item => {
    // 确保按照列名的顺序来推送数据  
    dataArray.push([
      item.nickName,
      item.submitTime,
      item.submitCount,
      item.a,
      item.s,
      item.p
    ]);
  });
  // 使用SheetJS的utils.aoa_to_sheet方法将二维数组数据转换为工作表  
  const ws = XLSX.utils.aoa_to_sheet(dataArray);
  // 创建一个新的工作簿，并将工作表添加到工作簿中  
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, "人员信息");

  // 直接使用XLSX.writeFile方法保存文件  
  XLSX.writeFile(wb, "人员信息.xlsx");
};
watch(drawer, (newVal) => {
  if (newVal === false) {
    window.location.reload(true);
  }
});







</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-header style="background-color: #fff">
        <div class="common-layout-header" style="display: flex; justify-content: space-between">
          <div class="common-layout-header-title">
            <img src="@/assets/img/列表.png" alt="" />作业管理
          </div>
          <div class="common-layout-header-button">
            <el-select placeholder="请选择班级" v-model="classId" style="width: 200px" @change="BytwoIdGetTaskList">
              <el-option label="全部">

              </el-option>
              <el-option v-for="item in classList" :key="item.classId" :label="item.className" :value="item.classId">
              </el-option>
            </el-select>

            <!-- 使用自定义样式的按钮 -->
            <div>
              <el-popover placement="bottom" :width="50" trigger="hover">
                <el-button size="small" text @click="exportToExcel">导出作业记录</el-button>
                <template #reference>
                  <el-button class="m-2"><el-icon>
                      <i><img src="@/assets/img/列表.png" style="width: 20px" />
                      </i></el-icon></el-button>
                </template>
              </el-popover>
            </div>
          </div>
        </div>
      </el-header>
      <el-main class="common-layout-main" style="width: 100%">
        <el-table :data="taskList" border style="width: 100%">
          <el-table-column prop="nickName" label="姓名" width="180"></el-table-column>
          <el-table-column prop="submitTime" label="提交时间"></el-table-column>
          <el-table-column prop="submitCount" label="提交次数"></el-table-column>
          <el-table-column prop="a" label="批复状态"></el-table-column>
          <el-table-column prop="s" label="评分"></el-table-column>
          <el-table-column prop="p" label="管理">
            <template #default="{ row }">
              <span @click="
                drawer = true;
              workpfList(row);
              ">{{ row.p }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
  </div>

  <el-drawer title="我是标题" v-model="drawer" :with-header="false" size="1000px">
    <div class="workTitle">
      <div class="head">
        <div class="head1">
          <span> {{ workList.nickName }}</span> <span>作业详情</span>
        </div>
      </div>
      <div class="title">
        <div class="headBox">
          <div class="title1">
            <span>题目:</span><br /><span>{{ workList.taskName }}
            </span>
          </div>
          <div class="title2">
            <span>参考答案:</span><br /><span>{{ workList.taskInfo
              }}</span>
          </div>
        </div>
        <div class="headBox">
          <div class="title3">
            <p>
              <span>来自学员:&nbsp;&nbsp;</span>
              <span class="name">{{ workList.nickName }}&nbsp;</span>
              <span>&nbsp;&nbsp;提交于:&nbsp;&nbsp;</span>
              <span class="time">{{ workList.submitTime }}</span>
            </p>
            <p>
              <span>附件:&nbsp;&nbsp;</span>
              <span class="file" @click="downloadFile(workList.attachmentUrl)">{{ workList.attachmentRealUrl }}</span>
            </p>
            <p>
              <span>缩略图:&nbsp;&nbsp;</span>
            <div class="demo-image__preview">
              <el-image style="width: 100px; height: 100px" :preview-src-list="srcList" :src="srcList[0]"
                :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :initial-index="4" fit="cover" />
            </div>
            </p>
          </div>
          <div class=" title4">
            <p>
              <span>内容:</span>
            </p>
            <span>{{ workList.taskTxt }}</span>
          </div>
        </div>
        <div class="headBox">
          <div class="title5">
            <span>评分与批复</span>
          </div>
          <div class="title6">
            <input type="text" min="0" max="100" step="1" placeholder="请输入您的评分 (0~100)"
              v-model="workList.score" /><span>分</span>
          </div>
          <div class="title7">
            <div class="title7-1">
              <textarea name="message" rows="10" cols="30" placeholder="请输入你的批复" v-model="workList.comment"
                @change="addSize">
            </textarea>
            </div>
            <div class="title7-2">
              <div class="title7-2-3">
                <span>{{ fontSize }}/2000</span>
              </div>
            </div>
          </div>
        </div>
        <div class="buttom">

          <input type="button" value="取消" @click="drawer = false" class="buttom2" />


          <input type="button" value="确认批复" @click="updateworklist" class="buttom3" />

        </div>
      </div>
    </div>
  </el-drawer>
</template>

<style lang="scss" scoped>
.demo-image__error .image-slot {
  font-size: 30px;
}

.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}

.demo-image__error .el-image {
  cursor: pointer;
  width: 100%;
  height: 200px;
}

.common-layout-header {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.common-layout-header-title {
  font-size: 20px;
  display: flex;
  font-family: "微软雅黑";
  align-items: center;
}

.common-layout-header-title img {
  width: 30px;
  display: flex;
}

.common-layout-header-button {
  display: flex;
  align-items: center;
  gap: 10px;
}

.icon-box {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  /* 调整盒子的宽度 */
  height: 32px;
  /* 调整盒子的高度 */
  border: 1px solid #ccc;
  /* 添加边框 */
  border-radius: 4px;
  /* 边框圆角 */
  background-color: #fff;
  /* 背景颜色 */
}

.icon-box:hover {
  cursor: pointer;
}

.title1 {
  height: 100px;
  overflow: auto;
}

.title2 {
  height: 150px;
  overflow: auto;
}

.title3 {
  line-height: 50px;
  margin-bottom: 20px;
}

.file {
  text-decoration: underline;
  color: blue;
  font-size: 14px;
  cursor: pointer;
}

.workImg {
  width: 200px;
}

.workImg img {
  display: block;
  width: 200px;
  cursor: pointer;
}

.title4 {
  height: 350px;
  overflow: auto;
}

.title5 {
  width: 95%;
  height: 40px;
  font-size: 16px;
  line-height: 40px;
}

.title6 {

  height: 50px;
  line-height: 50px;
  background-color: #00000005;
}

.title6 input {
  width: 95%;
  outline: none;
  border: none;
  text-indent: 1em;
  height: 50px;
  font-size: 15px;
  background-color: #00000005;
}

.title7 {
  margin-top: 20px;
  width: 100%;
  height: 22%;
  font-size: 16px;
  border-radius: 10px;
}

.title7-1 {
  margin-top: 10px;
  height: 150px;
  font-size: 16px;
  border-radius: 10px;
}

.title7-1 textarea {
  width: 100%;
  /* 宽度 */
  height: 100%;
  /* 高度 */
  resize: none;
  /* 允许用户调整文本区域的大小 */
  padding: 10px;
  /* 内边距 */
  border: 1px solid #ccc;
  /* 边框 */
  border-radius: 5px;
  /* 边框圆角 */
  font-size: 16px;
  /* 字体大小 */
  line-height: 1.5;
  /* 行高 */
  outline: none;
}

.title7-2 {
  margin-left: 10px;
  width: 95%;
  height: 30px;
  font-size: 16px;
  line-height: 30px;
}


.title7-2-3 {
  float: right;
  display: inline;
  width: 40px;
  height: 50px;
  font-size: 18px;
  margin-right: 40px;
  color: #000000a6;
}

.buttom {
  display: flex;
  justify-content: flex-end;
  width: 100%;
  height: 50px;
  font-size: 16px;
  line-height: 50px;
  margin-top: -30px;

}

.buttom2,
.buttom3 {
  height: 50px;
  line-height: 50px;
  height: 50px;
  cursor: pointer;
}

.buttom2 {
  border: none;
  width: 90px;
  height: 45px;
  font-size: 17px;
  border-radius: 10px;
  color: #000;
  margin-right: 5px;
}

.buttom3 {
  background-color: orangered;
  border: none;
  width: 90px;
  height: 45px;
  font-size: 17px;
  border-radius: 10px;
  color: #fff;
  margin-right: 10px;
}
</style>
